package com.example.e_book.DAO;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.e_book.entity.Book;
import com.example.e_book.DBUtil.DBHelper;

public class BookDAO {
    private final DBHelper dbHelper;

    public BookDAO(Context context) {
        dbHelper = new DBHelper(context);
    }

    public long addBook(Book book) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.COLUMN_BOOK_ID,book.getBookId());
        values.put(DBHelper.COLUMN_BOOK_TITLE, book.getTitle());
        values.put(DBHelper.COLUMN_BOOK_AUTHOR, book.getAuthor());
        values.put(DBHelper.COLUMN_CATEGORY, book.getCategory());
        values.put(DBHelper.COLUMN_BOOK_MAIN_CONTENT , book.getContentPath());// 保存文本内容路径
        values.put(DBHelper.COLUMN_BOOK_COVER_IMAGE, book.getCoverImagePath()); // 保存封面图片路径


        return db.insert(DBHelper.TABLE_BOOKS, null, values);
    }

    public Cursor getAllBooks() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query(DBHelper.TABLE_BOOKS, null, null, null, null, null, null);
    }

    public Cursor getBookById(int bookId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String[] columns = { DBHelper.COLUMN_BOOK_ID, DBHelper.COLUMN_BOOK_TITLE, DBHelper.COLUMN_BOOK_AUTHOR, DBHelper.COLUMN_BOOK_MAIN_CONTENT};
        String selection = DBHelper.COLUMN_BOOK_ID + "=?";
        String[] selectionArgs = { String.valueOf(bookId) };
        return db.query(DBHelper.TABLE_BOOKS, columns, selection, selectionArgs, null, null, null);
    }

    public Cursor getBooksByCategory(String category) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String[] columns = { DBHelper.COLUMN_BOOK_ID, DBHelper.COLUMN_BOOK_TITLE, DBHelper.COLUMN_BOOK_AUTHOR, DBHelper.COLUMN_CATEGORY,DBHelper.COLUMN_BOOK_MAIN_CONTENT,DBHelper.COLUMN_BOOK_COVER_IMAGE};
        String selection = DBHelper.COLUMN_CATEGORY + "=?";
        String[] selectionArgs = { category };
        return db.query(DBHelper.TABLE_BOOKS, columns, selection, selectionArgs, null, null, null);
    }
}
